<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="queryParams.taskType" placeholder="请选择任务类型" clearable>
                <el-option v-for="dict in pm_task_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="queryParams.projectId" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(projectList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="需求" prop="requireId">
              <el-select v-model="queryParams.requireId" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(requireList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="里程碑" prop="milestoneId">
              <el-select v-model="queryParams.milestoneId" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(milestoneList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="queryParams.owner" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="([key, value], index) in Object.entries(userList)"
                  :key="key"
                  :label="value"
                  :value="key"
                  @keyup.enter="handleQuery"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联人员" prop="relatedUsers">
              <el-select v-model="queryParams.relatedUsers" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="([key, value], index) in Object.entries(userList)"
                  :key="key"
                  :label="value"
                  :value="key"
                  @keyup.enter="handleQuery"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
                <el-option v-for="dict in pm_task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="版本号" prop="oldversionId">
              <el-select v-model="queryParams.oldversionId" filterable aria-placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(oldversionList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="新版本号" prop="newversionId">
              <el-select v-model="queryParams.newversionId" filterable aria-placeholder="请选择" clearable>
                <el-option v-for="dict in pm_task_newversion" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="开始时间" prop="startDate">
              <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择开始时间" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['pm:task:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['pm:task:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="主键" align="center" prop="id" v-if="true" /> -->
        <el-table-column v-if="columns[0].visible" label="标题" align="center" prop="title" width="240" :show-overflow-tooltip="true">
          <template #default="scope">
            <router-link :to="'/pm/task-data/index/' + scope.row.id" class="link-type">
              <span>{{ scope.row.title }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[1].visible" label="项目" align="center" prop="projectId" width="160" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(projectList, scope.row.projectId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="需求" align="center" prop="requireId" width="200" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(requireList, scope.row.requireId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="里程碑" align="center" prop="milestoneId" :show-overflow-tooltip="true" width="150">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(milestoneList, scope.row.milestoneId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].visible" label="内容" align="center" prop="content" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[5].visible" label="任务类型" align="center" prop="taskType" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="pm_task_type" :value="scope.row.taskType" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="优先级" align="center" prop="priority" width="100">
          <template #default="scope">
            <dict-tag :options="pm_priorities" :value="scope.row.priority" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="负责人" align="center" prop="owner" width="100">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(userList, scope.row.owner)" type="success">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[8].visible" label="开始时间" align="center" prop="startDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[17].visible" label="截止时间" align="center" prop="endDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} ') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[18].visible" label="耗时" align="center" prop="costTime" width="70" />
        <el-table-column v-if="columns[9].visible" label="任务标签" align="center" prop="tags">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(tagList, scope.row.tags)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[10].visible" label="关联人员" align="center" prop="relatedUsers">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredPostOptions(relevanceList, scope.row.relatedUsers)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" label="状态" align="center" prop="status" width="80px">
          <template #default="scope">
            <dict-tag :options="pm_task_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[19].visible" label="原版本号" align="center" prop="oldversionId" width="200" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(oldversionList, scope.row.oldversionId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="columns[20].visible" label="新版本号" align="center" prop="newversionId" width="200">
          <template #default="scope">
            <dict-tag :options="pm_task_newversion" :value="scope.rpw.newversionId"> </dict-tag>
          </template>
        </el-table-column> -->
        <el-table-column v-if="columns[12].visible" label="创建部门" align="center" prop="createDeptName" />
        <el-table-column v-if="columns[13].visible" label="创建者" align="center" prop="createByName" />
        <el-table-column v-if="columns[14].visible" label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[15].visible" label="修改者" align="center" prop="updateByName" />
        <el-table-column v-if="columns[16].visible" label="创建时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230px">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handView(scope.row)">预览</el-button>
            <el-button link type="primary" icon="RefreshLeft" @click="taskShare(scope.row)">分享</el-button>

            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pm:task:edit']">修改</el-button>

            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pm:task:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" filterable placeholder="请选择" @change="onSelectedDrug($event)">
                <el-option v-for="([key, value], index) in Object.entries(projectList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="需求" prop="requireId">
              <el-select v-model="form.requireId" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(requireList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="里程碑" prop="milestoneId">
              <el-select v-model="form.milestoneId" filterable placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(milestoneList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型">
                <el-option v-for="dict in pm_task_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="form.owner" filterable placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(userList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.startDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择任务类型">
                <el-option v-for="dict in pm_task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员" prop="roleIds">
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(relevanceList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 原版本号下拉框 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="原版本号" prop="oldversionId">
              <el-select v-model="originalVersion" placeholder="新任务暂无版本号" disabled>
                <el-option :label="originalVersion" :value="originalVersion"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 新版本号下拉框 -->
          <el-col :span="12">
            <!-- 版本号 -->
            <el-form-item label="新版本号">
              <div class="version-selectors">
                <!-- 主版本号 -->
                <el-select v-model="taskForm.majorVersion" filterable placeholder="主版本号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
                <span class="version-separator">.</span>
                <!-- 次版本号 -->
                <el-select v-model="taskForm.minorVersion" filterable placeholder="次版本号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
                <span class="version-separator">.</span>
                <!-- 修订号 -->
                <el-select v-model="taskForm.patchVersion" filterable placeholder="修订号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务标签" prop="tags">
              <el-select v-model="form.tags" filterable multiple placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(tagList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="相关图片">
          <imageUpload v-model="form.files" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="130" :height="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 预览任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.viewVisible" append-to-body>
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(projectList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="需求" prop="requireId">
              <el-select v-model="form.requireId" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(requireList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="里程碑" prop="milestoneId">
              <el-select v-model="form.milestoneId" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(milestoneList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型" disabled>
                <el-option v-for="dict in pm_task_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" disabled>
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="form.owner" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(userList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.startDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.endDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择截止时间"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="耗时" prop="costTime">
              <el-input v-model="form.costTime" placeholder="请输入耗时" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择任务类型" disabled>
                <el-option v-for="dict in pm_task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员" prop="roleIds">
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(relevanceList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务标签" prop="tags">
              <el-select v-model="form.tags" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(tagList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-row>
            <el-col :span="12">
              <el-form-item label="原版本号" prop="oldversionId">
                <el-select v-model="form.oldversionId" placeholder="请选择" disabled>
                  <el-option v-for="([key, value], index) in Object.entries(oldversionList)" :key="key" :label="value" :value="key"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新版本号" prop="newversionId">
                <el-select v-model="form.newversionId" placeholder="请选择" disabled>
                  <el-option v-for="dict in pm_task_newversion" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="12">
            <el-form-item label="创建部门" prop="projectCode">
              <el-input v-model="form.createDeptName" placeholder="请输入创建部门" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建者" prop="projectCode">
              <el-input v-model="form.createByName" placeholder="请输入创建者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="projectCode">
              <el-input v-model="form.createTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修改者">
              <el-input v-model="form.updateByName" placeholder="修改者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间">
              <el-input v-model="form.updateTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="相关图片" class="imageList">
          <imageUpload v-model="form.files" />
        </el-form-item>
        <el-form-item label="内容">
          <div class="content" v-html="form.content" @click="showImg($event)"></div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="imgDolg" v-show="imgPreview.show" @click.stop="imgPreview.show = false">
      <i class="Close" id="imgDolgClose" @click.stop="imgPreview.show = false"></i>
      <img @click.stop="imgPreview.show = true" :src="imgPreview.img" style="width: 50%; height: 80%" />
    </div>
  </div>
</template>
<script setup name="Task" lang="ts">
import { listTask, getTask, delTask, addTask, updateTask } from '@/api/pm/task';
import { TaskVO, TaskQuery, TaskForm } from '@/api/pm/task/types';
import { formatDate } from '../../../utils/index';
import api from '@/api/system/user/index';
import { getUserProfile } from '@/api/system/user/index';
import { UserVO } from '@/api/system/user/types';
import { useRouter } from 'vue-router';
import directive from '@/directive';
import { SCOPE } from 'element-plus';
import { ref } from 'vue';
import { saveTask } from '@/api/pm/task';
const router = useRouter();
const state = ref<State>({
  user: {}
});
interface State {
  user: Partial<UserVO>;
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pm_priorities, pm_task_type, pm_task_status, pm_task_newversion } = toRefs<any>(
  proxy?.useDict('pm_priorities', 'pm_task_type', 'pm_task_status', 'pm_task_newversion')
);
const projectList = ref([]);
const requireList = ref([]);
const milestoneList = ref([]);
const userList = ref([]);
const tagList = ref([]);
const oldversionList = ref([]);
const newversionList = ref([]);
const relevanceList = ref([]);
const taskList = ref<TaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const loggedder = ref();
const queryFormRef = ref<ElFormInstance>();
const taskFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  viewVisible: false
});
const imgPreview = ref({
  img: '', // 存储预览图片的URL
  show: false // 控制模态框的显示状态
});
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `标题`, visible: true, children: [] },
  { key: 1, label: `项目`, visible: true, children: [] },
  { key: 2, label: `需求`, visible: true, children: [] },
  { key: 3, label: `里程碑`, visible: true, children: [] },
  { key: 4, label: `内容`, visible: false, children: [] },
  { key: 5, label: `任务类型`, visible: true, children: [] },
  { key: 6, label: `优先级`, visible: true, children: [] },
  { key: 7, label: `负责人`, visible: true, children: [] },
  { key: 8, label: `开始时间`, visible: true, children: [] },
  { key: 9, label: `任务标签`, visible: false, children: [] },
  { key: 10, label: `关联人员`, visible: false, children: [] },
  { key: 11, label: `状态`, visible: true, children: [] },
  { key: 12, label: `创建部门`, visible: false, children: [] },
  { key: 13, label: `创建者`, visible: false, children: [] },
  { key: 14, label: `创建时间`, visible: false, children: [] },
  { key: 14, label: `修改者`, visible: false, children: [] },
  { key: 16, label: `创建时间`, visible: false, children: [] },
  { key: 17, label: `截止时间`, visible: true, children: [] },
  { key: 18, label: `耗时`, visible: false, children: [] },
  { key: 19, label: `原版本号`, visible: true, children: [] },
  { key: 20, label: `新版本号`, visible: true, children: [] }
]);
const initFormData: TaskForm = {
  id: undefined,
  title: undefined,
  projectId: undefined,
  requireId: undefined,
  milestoneId: undefined,
  content: undefined,
  taskType: undefined,
  priority: undefined,
  owner: undefined,
  startDate: undefined,
  files: undefined,
  tags: undefined,
  oldversionId: undefined,
  newversionId: undefined,
  relatedUsers: undefined,
  status: undefined
};
const data = reactive<PageData<TaskForm, TaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    title: undefined,
    projectId: undefined,
    requireId: undefined,
    milestoneId: undefined,
    taskType: undefined,
    priority: undefined,
    owner: undefined,
    startDate: undefined,
    status: undefined,
    relatedUsers: undefined,
    oldversionId: undefined,
    newversionId: undefined,
    params: {}
  },
  rules: {
    title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目id不能为空', trigger: 'change' }],
    // requireId: [
    //   { required: true, message: "需求不能为空", trigger: "change" }
    // ],
    milestoneId: [{ required: true, message: '里程碑id不能为空', trigger: 'change' }],
    taskType: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
    priority: [{ required: true, message: '优先级不能为空', trigger: 'change' }],
    owner: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
    startDate: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    oldversionId: [{ required: true, message: '原版本号不能为空', trigger: 'change' }],
    newversionId: [{ required: true, message: '新版本号不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
const showImg = (e) => {
  if (e.target.tagName === 'IMG' && e.target.src) {
    imgPreview.value.img = e.target.src; // 更新预览图片的URL
    imgPreview.value.show = true; // 显示模态框
  }
};
/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.isAsc = 'desc';
  queryParams.value.orderByColumn = 'id';
  const res = await listTask(queryParams.value);
  taskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  taskFormRef.value?.resetFields();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: TaskVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  form.value.owner = loggedder.value;
  dialog.title = '添加任务';
  form.value.taskType = 'dev_function';
  form.value.priority = 'middle';
  form.value.status = 'ready';
  const current = new Date().toISOString();
  const currentTime = formatDate(current);
  form.value.startDate = currentTime;
};
/** 分享按钮操作 */
const taskShare = async (row?: TaskVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  router.push({ path: `/pm/task-share/index/${_id}` });
};
/** 修改按钮操作 */
const handleUpdate = async (row?: TaskVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTask(_id);
  if (res.data.relatedUsers) {
    res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  } else {
    res.data.relatedUsers = '';
  }
  res.data.tags = JSON.parse(res.data.tags);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改任务';
  const data1 = await api.affiliatePperson('project');
  projectList.value = data1.data;
  const data2 = await api.affiliatePperson('require');
  requireList.value = data2.data;
  const data3 = await api.affiliatePperson('milestone');
  milestoneList.value = data3.data;
  const data4 = await api.affiliatePperson('user');
  userList.value = data4.data;
  relevanceList.value = data4.data;
  const data5 = await api.affiliatePperson('tag');
  tagList.value = data5.data;
  const data6 = await api.affiliatePperson('oldversion');
  oldversionList.value = data6.data;
  const data7 = await api.affiliatePperson('newversion');
  newversionList.value = data7.data;
};
/** 预览按钮操作 */
const handView = async (row?: TaskVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTask(_id);
  if (res.data.relatedUsers) {
    res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  }
  Object.assign(form.value, res.data);
  dialog.viewVisible = true;
  dialog.title = '预览任务';
  const data1 = await api.affiliatePperson('project');
  projectList.value = data1.data;
  const data2 = await api.affiliatePperson('require');
  requireList.value = data2.data;
  const data3 = await api.affiliatePperson('milestone');
  milestoneList.value = data3.data;
  const data4 = await api.affiliatePperson('user');
  userList.value = data4.data;
  relevanceList.value = data4.data;
  const data5 = await api.affiliatePperson('tag');
  tagList.value = data5.data;
  const data6 = await api.affiliatePperson('oldversion');
  oldversionList.value = data6.data;
  const data7 = await api.affiliatePperson('newversion');
  newversionList.value = data7.data;
};
const onSelectedDrug = async (e) => {
  // const queryReview = {
  //       proId: e,
  //     };
  form.value.milestoneId = '';
  console.log('drugId', e);
  try {
    const data3 = await api.linkagePperson('milestone', e);
    milestoneList.value = data3.data;
  } catch (error) {
    console.error('Error fetching modules:', error);
    // 可以在这里添加错误处理逻辑，比如重置 moduleList 或显示错误消息
  }
};
/** 提交按钮 */
const submitForm = () => {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.log('关联人员', form.value.relatedUsers);
      if (form.value.relatedUsers) {
        form.value.relatedUsers = JSON.stringify(form.value.relatedUsers);
      } else {
        form.value.relatedUsers = '';
      }

      form.value.tags = JSON.stringify(form.value.tags);
      if (form.value.id) {
        await updateTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: TaskVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除任务编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTask(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'pm/task/export',
    {
      ...queryParams.value
    },
    `task_${new Date().getTime()}.xlsx`
  );
};
/** 加载下拉列表数据 */
const getSelectList = async () => {
  const data1 = await api.affiliatePperson('project');
  projectList.value = data1.data;
  const data2 = await api.affiliatePperson('require');
  requireList.value = data2.data;
  const data3 = await api.affiliatePperson('milestone');
  milestoneList.value = data3.data;
  const data4 = await api.affiliatePperson('user');
  userList.value = data4.data;
  relevanceList.value = data4.data;
  const data5 = await api.affiliatePperson('tag');
  tagList.value = data5.data;
  const data6 = await api.affiliatePperson('oldversion');
  oldversionList.value = data6.data;
  const data7 = await api.affiliatePperson('newversion');
  newversionList.value = data7.data;
};
const filteredRequireList = (data, requireId: string | number) => {
  return Object.entries(data).filter(([key]) => key === requireId);
};
const filteredPostOptions = (data, param: string) => {
  let parsed = JSON.parse(param);
  parsed = Array.isArray(parsed) ? parsed : [];
  return Object.entries(data).filter(([key]) => parsed.includes(key));
};
const getUser = async () => {
  const res = await getUserProfile();
  state.value.user = res.data.user;
  loggedder.value = state.value.user.userId;
  // console.log("用户信息", state.value.user)
};
onMounted(() => {
  getList();
  getSelectList();
  getUser();
});
//表单数据
const taskForm = ref({
  majorVersion: null, //主版本号
  minorVersion: null, //次版本号
  patchVersion: null //修订号
});
//原版本号(合并为一个字符串)
const originalVersion = ref(''); //初始为空
//版本号选择
const versionNumbers = ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); //可根据需求调整
// methods:{

// }
</script>
<style scoped>
:deep(img) {
  /* 样式内容 */
  width: 100px;
  height: 100px;
}
:deep(.ql-editor p) {
  display: flex;
  align-items: center;
  /* 水平居中（如果需要） */
  /* 样式内容 */
  width: 100%;
}
:deep(.ql-editor li) {
  display: flex;
  align-items: center;
  /* 水平居中（如果需要） */
  /* 样式内容 */
  width: 100%;
}
:deep(.ql-align-center) {
  display: flex;
  align-items: center;
  /* 水平居中（如果需要） */
  /* 样式内容 */
  width: 100%;
}
.content {
  border: 1px solid #d3d3d3;
  width: 100%;
}
.content img {
  max-width: 20%;
  margin-right: 5px;
  margin-left: 5px;
}
:deep(.content p) {
  display: flex;
  align-items: center;
  /* 水平居中（如果需要） */
  /* 样式内容 */
  width: 100%;
}
a {
  cursor: pointer; /* 或者 cursor: hand; 但 pointer 是更标准和推荐的 */
}
.content .ql-syntax {
  white-space: pre-line;
  word-wrap: break-word;
  /* 允许在适当的位置换行 */
  overflow-wrap: break-word;
}

.imgDolg {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.8);
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

#imgDolgClose {
  position: fixed;
  top: 25px;
  cursor: pointer;
  right: 4%;
  font-size: 50px;
  color: white;
}
/* 隐藏删除按钮 */
:deep(.imageList .el-upload-list__item-delete) {
  display: none !important;
}
:deep(.imageList .el-icon--close-tip) {
  display: none !important;
}
.app-container {
  padding: 20px;
}

.version-selectors {
  display: flex;
  align-items: center;
}

.version-selector {
  width: 102px; /* 每个下拉框宽度为 80px */
}

.version-separator {
  margin: 0 8px;
  font-size: 16px;
  font-weight: bold;
}
</style>
